/**
1、实现一个 斐波那契数列 函数
*/

function fib(max) {
    var
        t,
        a = 0,
        b = 1,
        arr = [0, 1];
    while (arr.length < max) {
        t = a + b;
        a = b;
        b = t;
        arr.push(t);
    }
    return arr;
}


// console.log(fib(10));

// 改写
function* fib(max) {
    var
        t,
        a = 0,
        b = 1,
        n = 1;
    while (n < max) {
        yield a;
        t = a + b;
        a = b;
        b = t;
        n ++;
    }
    return a;
}

var f = fib(5);
/*
console.log(f.next());
console.log(f.next());
console.log(f.next());
console.log(f.next());
console.log(f.next());
*/

// { value: 0, done: false }
// { value: 1, done: false }
// { value: 1, done: false }
// { value: 2, done: false }
// { value: 3, done: true }

/*
for(var x of fib(5)){
 console.log(x);
}
*/

// ================================

function* auto_increment(){
	var id = 0;
	while(true){
		yield id++;
	}
	return id++;
}

var generator = auto_increment();
/*console.log(generator.next());
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());
console.log(generator.next());*/

/*生成一个自增id(需要保存状态)*/

// 改用闭包实现（保存状态）

function auto_id(){
	var id= 0;
	return function(){
		return id++;
	}
}

var gid = auto_id();
console.log(gid());
console.log(gid());
console.log(gid());
console.log(gid());
console.log(gid());



